#include "transfile.h"

int putsFile(int peerfd, char *para)
{
	// 1. 读取本地文件
	int fd = open(para, O_RDWR);
	ERROR_CHECK(fd, -1, "open");

	// 2. 先发文件名
	sendMsg(peerfd,para);

	// 3. 再发文件内容
	// 3.1 获取文件的长度
	struct stat st;
	fstat(fd, &st);
	printf("file's length: %ld\n", st.st_size);
	// printf("sizeof(st.st_size): %ld\n", sizeof(st.st_size));
	send(peerfd, &st.st_size, 8, MSG_WAITALL);

	//3.2收服务器端文件长度
	size_t sendSize = 0;
	recvCircle(peerfd,(char*)&sendSize,8);
	
	//3.3断点续传
	lseek(fd,sendSize,SEEK_SET);
	train_t train;
	while (sendSize < st.st_size)
	{
		memset(&train, 0, sizeof(train));
		//从本地文件中读取,将其放入train
		int ret = read(fd, train.buff, sizeof(train.buff));
		train.length = ret;
		//发送数据给到对端
		ret = send(peerfd, &train, 4 + train.length, MSG_WAITALL);
		if (ret > 0)
		{
			sendSize += (ret - 4);
		}
		else
		{
			perror("send");
			break;
		}
		//先传一部分，构造一个断点续传情况
		//sleep(10);
	}
	close(fd);
	return sendSize - st.st_size;
}

int getsFile(int peerfd, char *para)
{
	// 1. 先发文件名，之后可以发md5值。
	train_t train;
	memset(&train, 0, sizeof(train));
	train.length = strlen(para); // 100
	strcpy(train.buff, para);
	int ret = send(peerfd, &train, 4 + train.length, MSG_WAITALL); // 104

	// 2.在本地建立文件
	int fd = open(para, O_RDWR | O_CREAT | O_TRUNC, 0664);
	ERROR_CHECK(fd, -1, "open");

	// 3. 再接收文件内容
	// 3.1 先接文件长度
	size_t filelength = 0;

	recvCircle(peerfd, (char *)&filelength, 8);
	printf("filecontent length: %ld\n", filelength);

	// 3.2 再接文件内容
	int length = 0;
	size_t recvSize = 0;
	while (recvSize < filelength)
	{
		char buff[1024] = {0};
		recvCircle(peerfd, (char *)&length, 4);
		recvCircle(peerfd, buff, length);
		// 3. 写入本地
		write(fd, buff, length);
		recvSize += length;
	}
	close(fd);
	return recvSize - filelength;
}


int recvCircle(int fd, char *buff, int length)
{
	char *pbuf = buff;
	int left = length;
	int ret = 0;
	while (left > 0)
	{
		ret = recv(fd, pbuf, left, 0);
		if (0 == ret)
		{
			close(fd);
			break;
		}
		else if (ret == -1 && errno == EINTR)
		{
			continue;
		}
		else if (ret == -1)
		{
			perror("recv");
			break;
		}
		else
		{ // > 0
			pbuf += ret;
			left -= ret;
		}
		// printf("recv %f%%\r",(float)ret/left * 100);
	}
	return length - left;
}